import json
import os
import cv2
import base64
import numpy as np
import re


def _base64_to_image(base64_code: str) -> cv2.Mat:
    # base64解码
    img_data = base64.b64decode(base64_code)
    # 转换为np数组
    img_array = np.frombuffer(img_data, np.uint8)
    # 转换成opencv可用格式
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)

    return img


def get_img(name: str) -> cv2.Mat:
    # 读取JSON文件
    current_directory = os.getcwd()

    relative_path = 'data\img.json'
    full_path = os.path.join(current_directory, relative_path)

    with open(full_path, 'r', encoding='utf-8') as file:
        data = json.load(file)

    img_datas = data['icons1'] + data['icons2']
    for img_data in img_datas:
        searchObj = re.search(name, img_data['name'], re.M | re.I)
        if searchObj:
            image = _base64_to_image(img_data['value'])
    return image

if __name__ == '__main__':
    image = get_img("图标")
    cv2.imwrite("图标.png", image)
